package com.gable.report.service.impl;

import com.gable.report.common.util.CalculationUtil;
import com.gable.report.common.util.ReturnResultUtil;
import com.gable.report.dao.IChartsForHospitalCostDao;
import com.gable.report.model.ChartsForCost;
import com.gable.report.model.ChartsHospitalQuery;
import com.gable.report.model.QueryInterval;
import com.gable.report.service.ChartsForHospitalCostService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gable.report.util.ChartsUtil.getParamMap;


/**
 * Created by lvdouStart on 2017/7/26.
 * 区报表维修情况service实现类
 */
@Service
public class ChartsForHospitalCostServiceImpl implements ChartsForHospitalCostService {

    private final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    IChartsForHospitalCostDao chartsForHospitalCostDao;

    @Override
    public ReturnResultUtil queryDepartments(Long hospitalId, ChartsHospitalQuery chartsHospitalQuery) {
        try {
            Map<String,Object> paramMap = getParamMap(hospitalId, chartsHospitalQuery);
            List<ChartsForCost> chartsFoCosts = chartsForHospitalCostDao.queryDepartments(paramMap);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list",chartsFoCosts);
            if(!CollectionUtils.isEmpty(chartsFoCosts)){
                pushAvgValue(chartsFoCosts.size(),chartsFoCosts,map);
            }
            return new ReturnResultUtil(1,"success",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }

    }

    @Override
    public ReturnResultUtil queryDeviceTypes(Long hospitalId,ChartsHospitalQuery chartsHospitalQuery) {
        try {
            Map<String,Object> paramMap = getParamMap(hospitalId, chartsHospitalQuery);
            List<ChartsForCost> chartsFoCosts = chartsForHospitalCostDao.queryDeviceTypes(paramMap);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list",chartsFoCosts);
            if(!CollectionUtils.isEmpty(chartsFoCosts)){
                //获取平均值
                pushAvgValue(chartsFoCosts.size(),chartsFoCosts,map);
            }
            return new ReturnResultUtil(1,"success",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }

    @Override
    public ReturnResultUtil queryBrand(Long hospitalId,ChartsHospitalQuery chartsHospitalQuery) {
        try {
            Map<String,Object> paramMap = getParamMap(hospitalId, chartsHospitalQuery);
            List<ChartsForCost> chartsFoCosts = chartsForHospitalCostDao.queryBrand(paramMap);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list",chartsFoCosts);
            if(!CollectionUtils.isEmpty(chartsFoCosts)){
                //获取平均值
                pushAvgValue(chartsFoCosts.size(),chartsFoCosts,map);
            }
            return new ReturnResultUtil(1,"success",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }

    @Override
    public ReturnResultUtil queryDeviceModels(Long hospitalId,ChartsHospitalQuery chartsHospitalQuery) {
        try {
            Map<String,Object> paramMap = getParamMap(hospitalId, chartsHospitalQuery);
            List<ChartsForCost> chartsFoCosts = chartsForHospitalCostDao.queryDeviceModels(paramMap);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list",chartsFoCosts);
            if(!CollectionUtils.isEmpty(chartsFoCosts)){
                //获取平均值
                pushAvgValue(chartsFoCosts.size(),chartsFoCosts,map);
            }
            return new ReturnResultUtil(1,"success",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }

    @Override
    public ReturnResultUtil queryOverview(Long hospitalId,ChartsHospitalQuery chartsHospitalQuery) {
        try {
            Map<String,Object> paramMap = getParamMap(hospitalId, chartsHospitalQuery);
            Map<String, Object> hospitalPerformance = chartsForHospitalCostDao.queryHospitalPerformance(paramMap);
            if(hospitalPerformance != null){
                Double income = Double.parseDouble(hospitalPerformance.get("jnIncome").toString());    //今年收入
                Double expenditure =Double.parseDouble(hospitalPerformance.get("jnExpenditure").toString());   //今年支出
                //收入和支出都有
                if(income > 0 && expenditure > 0){
                    paramMap.put("queryType",2);
                }
                else
                    //只有收入
                    if(income > 0 && expenditure == 0){
                        paramMap.put("queryType",3);
                    }
                    else
                        //只有支出
                        if(income == 0 && expenditure > 0){
                            paramMap.put("queryType",4);
                        }

            }
            //收入和支出都没有
            else{
                paramMap.put("queryType",2);
            }
            //查找区间
            Map<String,Object> intervalParamMap = new HashMap<>();
            intervalParamMap.put("id",hospitalId);
            intervalParamMap.put("type",paramMap.get("queryType"));
            QueryInterval qi = chartsForHospitalCostDao.queryInterval(intervalParamMap);
            if(qi == null){
                intervalParamMap.put("id",1001);
                qi = chartsForHospitalCostDao.queryInterval(intervalParamMap);
            }
            paramMap.put("queryMax",qi.getQueryMax());
            paramMap.put("queryMin",qi.getQueryMin());

            Map OverviewMap_1 = chartsForHospitalCostDao.queryOverview_1(paramMap);
            Map OverviewMap_2 = chartsForHospitalCostDao.queryOverview_2(paramMap);
            Map OverviewMap_3 = chartsForHospitalCostDao.queryOverview_3(paramMap);
            Map OverviewMap_4 = chartsForHospitalCostDao.queryOverview_4(paramMap);

            Map nullmap = new HashMap();
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("overview_1",OverviewMap_1==null?nullmap:OverviewMap_1);
            map.put("overview_2",OverviewMap_2==null?nullmap:OverviewMap_2);
            map.put("overview_3",OverviewMap_3==null?nullmap:OverviewMap_3);
            map.put("overview_4",OverviewMap_4==null?nullmap:OverviewMap_4);

            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("list",map);
            return new ReturnResultUtil(1,"success",resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }

    @Override
    public ReturnResultUtil queryAssets(Long hospitalId,ChartsHospitalQuery chartsHospitalQuery) {
        try {
            Map<String,Object> paramMap = getParamMap(hospitalId, chartsHospitalQuery);
            List<ChartsForCost> chartsFoCosts = chartsForHospitalCostDao.queryAssets(paramMap);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list",chartsFoCosts);
            return new ReturnResultUtil(1,"success",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
    }

    @Override
    public ReturnResultUtil queryForMonth(Long hospitalId,ChartsHospitalQuery chartsHospitalQuery) {
        try {
            Map<String,Object> paramMap = getParamMap(hospitalId, chartsHospitalQuery);
            //今年数据
            List<Map<String,Object>> thisYearData = chartsForHospitalCostDao.queryForMonth(paramMap);
            Integer curYear = Integer.parseInt(paramMap.get("curYear").toString());
            paramMap.put("curYear",curYear-1);  //去年
            //去年数据
            List<Map<String,Object>> lastYearData = chartsForHospitalCostDao.queryForMonth(paramMap);
            if(!CollectionUtils.isEmpty(thisYearData)){
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("thisYearData",thisYearData);
                map.put("lastYearData",lastYearData);
                List<Double> incomeYoyList = new ArrayList<>(); //收入同比列表
                List<Double> expendYoyList = new ArrayList<>(); //支出同比列表
                List<Double> szPercentageYoyList = new ArrayList<>(); //收支比同比列表
                for(int i=0;i<12;i++){
                    double thisIncome = (Double) thisYearData.get(i).get("totalIncome");
                    double lastIncome = (Double) lastYearData.get(i).get("totalIncome");
                    //收入同比
                    double incomeYoy;
                    if(thisIncome == 0.0 && lastIncome == 0.0){
                        incomeYoy = 0.0;
                    }else if(lastIncome == 0.0){
                        incomeYoy = 100.0;
                    }else{
                        incomeYoy = (thisIncome - lastIncome)*100.0/lastIncome;
                    }
                    double thisExpenditure = (Double) thisYearData.get(i).get("totalExpenditure");
                    double lastExpenditure = (Double) lastYearData.get(i).get("totalExpenditure");
                    //支出同比
                    double expendYoy;
                    if(thisExpenditure == 0.0 && lastExpenditure == 0.0){
                        expendYoy = 0.0;
                    }else if(lastExpenditure == 0.0){
                        expendYoy = 100.0;
                    }else{
                        expendYoy =  (thisExpenditure - lastExpenditure)*100.0/lastExpenditure;
                    }
                    double thisSzPercentage = (Double) thisYearData.get(i).get("szPercentage");
                    double lastSzPercentage = (Double) lastYearData.get(i).get("szPercentage");
                    //收支比同比
                    double szPercentageYoy;
                    if(thisSzPercentage == 0.0 && lastSzPercentage == 0.0){
                        szPercentageYoy = 0.0;
                    }else if(lastSzPercentage == 0.0){
                        szPercentageYoy = 100.0;
                    }else{
                        szPercentageYoy =  (thisSzPercentage - lastSzPercentage)*100.0/lastSzPercentage;
                    }
                    incomeYoyList.add(incomeYoy);
                    expendYoyList.add(expendYoy);
                    szPercentageYoyList.add(szPercentageYoy);
                }
                map.put("incomeYoy",incomeYoyList);
                map.put("expendYoy",expendYoyList);
                map.put("szPercentageYoy",szPercentageYoyList);
                return new ReturnResultUtil(1,"success",map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常");
        }
        return new ReturnResultUtil(1,"success",null);
    }

    @Override
    public ReturnResultUtil queryInterval(Map<String, Object> paramMap) {
        try {
            QueryInterval qi = chartsForHospitalCostDao.queryInterval(paramMap);
            if(qi == null){
                paramMap.put("id",1001);
                qi = chartsForHospitalCostDao.queryInterval(paramMap);
            }
            return new ReturnResultUtil(1,"success",qi);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnResultUtil(0,"查询异常",null);
        }
    }

    @Override
    public Map<String, Object> queryHospitalPerformance(Map<String,Object> paramMap) {
        try {
            Map<String, Object> hospitalPerformance = chartsForHospitalCostDao.queryHospitalPerformance(paramMap);
            return hospitalPerformance;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    public void yearUtil(Map<String,Object> paramMap){
//        //处理今年和去年 2017-01-09 15:22:16.000
//        String year = paramMap.get("year")+"";//今年
//        String yearStart = "-01-01 00:00:00";//年区间 2017-01-01 00:00:00
//        String yearEnd = "-12-31 23:59:59";//年区间 2017-12-31 23:59:59
//        if("null".equals(year) || StringUtil.isEmpty(year)){
//            //默认今年
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
//            year = sdf.format(new Date());
//        }
//        String lyear = Integer.parseInt(year)-1+"";//去年
//        String thisYearStart = year+yearStart;
//        String thisYearEnd = year+yearEnd;
//        String lastYearStart = lyear+yearStart;
//        String lastYearEnd = lyear+yearEnd;
//        paramMap.put("thisYearStart",thisYearStart);
//        paramMap.put("thisYearEnd",thisYearEnd);
//        paramMap.put("lastYearStart",lastYearStart);
//        paramMap.put("lastYearEnd",lastYearEnd);
//    }

    //平均值
    public void pushAvgValue(Integer num,List<ChartsForCost> chartsForCosts,Map<String,Object> map){
        String totalIncome = "0";
        String totalExpenditure = "0";
        String szPercentage = "0";
        String totalAssetsAmount = "0";

        for(ChartsForCost cfs : chartsForCosts){
            totalIncome = CalculationUtil.addForCost(totalIncome,cfs.getJnIncome().toString());
            totalExpenditure = CalculationUtil.addForCost(totalExpenditure,cfs.getJnExpenditure().toString());
            szPercentage = CalculationUtil.addForCost(szPercentage,cfs.getJnszPercentage().toString());
            totalAssetsAmount = CalculationUtil.addForCost(totalAssetsAmount,cfs.getJnAssetsAmount().toString());
        }

        String avgIncome = CalculationUtil.divide(totalIncome,num,3);
        String avgExpenditure = CalculationUtil.divide(totalExpenditure,num,3);
        String avgSzPercentage = CalculationUtil.divide(szPercentage,num,3);
        String avgAssetsAmount = CalculationUtil.divide(totalAssetsAmount,num,3);

        map.put("avgIncome",avgIncome); //平均收入
        map.put("avgExpenditure",avgExpenditure);   //平均支出
        map.put("avgSzPercentage",avgSzPercentage); //平均收支比
        map.put("avgAssetsAmount",avgAssetsAmount); //平均设备金额
    }
}
